Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

231
Visualizações
Is it bad to have "number" as object keys?

I just searched through SO and it looks like everybody agrees with the idea that JavaScript and TypeScript are not supporting using numbers as keys in an object directly. But somehow my fellow developer has used some objects with numeric keys in our Angular project which are working just fine as other objects. This is what they look like.

{
   1: 1,
   2: 0,
   3: 2
}

And calling the value in a form like obj[2] does not have a problem at the moment. Just wondering if it is the right way to do it, and how well this usage is supported?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Its fine, as in - its legal, as its how arrays work, though one thing to watch out for is that arrays will ensure the key is incremental, starting at 0, whereas a numerical key in an object will not, and WILL be misleading for other developers when they cant understand why obj[1] doesnt always live beside obj[2] etc, and by that I mean the use of within loops etc and simply incrementing the index by one each time. So, personally i wouldnt recommend it due to it looking like an array, but it not actually being an array...

Side - If you are trying to mimic an array, but want an index starting at 1, just use an array as normal and have your code just handle the offset each time. Arrays come with many functions, like length, sort, find etc that an object will not

about 4 years ago · Juan Pablo Isaza Relatório

0

In javascript keys in object are string type and if you have obj[1] it will automatically turn into obj['1'] but not the same in Map

const obj = {}

obj[1] = 'one';

console.log(obj[1]);
// output: "one"
console.log(obj['1']);
// output: "one"

obj['1'] = 'one string';

console.log(obj[1]);
// output: "one string"
console.log(obj['1']);
// output: "one string"

const map = new Map();
map.set(1, 'one');
map.set('1', 'one string');

console.log(map.get(1));
// output: "one"
console.log(map.get('1'));
// output: "one string"
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda